# coding=utf-8
# author:xc
# datetime:2018/8/17 11:55

from dbConnection.MysqlConn import Mysql
from . import html
from app import util, upload_files
from flask import request


# 首页标题
@html.route('/api/home/title', methods=['POST', 'GET'])
def api_home_title():
    try:
        mysql = Mysql()
        sql = "select * from girl_subject where status=1"
        result = mysql.getAll(sql, None)
        mysql.dispose()
        title = []
        code = util.CODE_EMPTY
        if result:
            code = util.CODE_SUCCESS
            title = result
    except Exception as e:
        print e
        title = []
        code = util.CODE_ERROR
    data = {
        'code': code,
        'title': title
    }
    return util.to_json(data)


# 首页推荐
@html.route('/api/home/recommend', methods=['POST', 'GET'])
def api_home_recommend():
    try:
        mysql = Mysql()
        recommendSql = "select b.* from girl_recommend as a left join girl_course as b " \
                       "on a.cid=b.cid where b.status= 1 order by a.addTime desc  "
        publicSql = "select b.* from girl_public as a left join girl_course as b " \
                    "on a.cid=b.cid where b.status=1 order by a.addTime desc"
        supremeSql = "select b.* from girl_supreme as a left join girl_course as b " \
                     "on a.cid=b.cid where b.status=1 order by a.addTime desc"
        recommendRes = mysql.getAll(recommendSql, None)
        publicRes = mysql.getAll(publicSql, None)
        supremeRes = mysql.getAll(supremeSql, None)
        mysql.dispose()
        supreme = []
        public = []
        recommend = []
        code = util.CODE_EMPTY
        if recommendRes:
            code = util.CODE_SUCCESS
            for x in recommendRes:
                if not x['cover'].startswith('http'):
                    x['cover'] = upload_files.baseUrl + x['cover']
            recommend = recommendRes
        if supremeRes:
            for x in supremeRes:
                if not x['cover'].startswith('http'):
                    x['cover'] = upload_files.baseUrl + x['cover']
            supreme = supremeRes
        if publicRes:
            for x in publicRes:
                if not x['cover'].startswith('http'):
                    x['cover'] = upload_files.baseUrl + x['cover']
            public = publicRes
    except Exception as e:
        print e
        supreme = []
        public = []
        recommend = []
        code = 500
    data = {
        'recommend': recommend,
        'public': public,
        'supreme': supreme,
        'code': code
    }
    return util.to_json(data)


# 获取心灵成长
@html.route('/api/girl/spiritual', methods=['POST', 'GET'])
def api_girl_spiritual():
    try:
        sid = request.values.get('sid')
        mysql = Mysql()
        sql1 = "select typeName,info  from girl_subject where sid='%s' " % sid
        sql = "select a.tid ,a.courseName,a.info from girl_type as a where a.status=1 and sid ='%s'" % sid
        title = mysql.getOne(sql1, None)
        result = mysql.getAll(sql, None)
        code = util.CODE_EMPTY
        data = []
        if result:
            code = util.CODE_SUCCESS
            for x in range(0, len(result)):
                data_title = dict()
                data_title['name'] = result[x]['courseName']
                data_title['tid'] = result[x]['tid']
                if result[x]['info'] is None:
                    data_title['info'] = ""
                else:
                    data_title['info'] = result[x]['info']
                list_detail = []
                sql2 = " select b.* from  girl_course as b where b.status=1 and b.tid='%s' order by b.addTime desc limit 0,%d " % (
                    result[x]['tid'], 10)
                detail = mysql.getAll(sql2, None)
                for k in detail:
                    data_detail = dict()
                    data_detail['cid'] = k['cid']
                    data_detail['courseName'] = k['courseName']
                    data_detail['flag'] = k['flag']
                    if not k['cover'].startswith('http'):
                        data_detail['cover'] = upload_files.baseUrl + k['cover']
                    else:
                        data_detail['cover'] = k['cover']
                    data_detail['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                    data_detail['info'] = k['info']
                    list_detail.append(data_detail)
                data_title['list_content'] = list_detail
                data.append(data_title)
        mysql.dispose()
    except Exception as e:
        print e
        data = []
        code = util.CODE_ERROR
        title = {}
    data = {
        'code': code,
        'data': data,
        "title": title
    }
    return util.to_json(data)


# 更多课程
@html.route('/api/more/course', methods=['POST', 'GET'])
def api_more_course():
    try:
        tid = request.values.get('tid')
        page = request.values.get('page', default=1)
        index = request.values.get('index', default=0)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        mysql = Mysql()
        sql1 = "select courseName,sid from girl_type where tid='%s'" % tid
        sql = "select * from girl_course where tid='%s' and status=1 order by addTime desc limit %d, %d" % (
            tid, num, util.PAGE_NUM)
        sql2 = "select count(*) from girl_course where tid='%s'and status=1 " % tid
        result = mysql.getAll(sql, None)
        name = mysql.getOne(sql1, None)
        title = name['courseName']
        sid = name['sid']
        count = mysql.getOne(sql2, None)
        mysql.dispose()
        res = []
        code = util.CODE_EMPTY
        if result:
            code = util.CODE_SUCCESS
            for k in result:
                data_detail = dict()
                data_detail['cid'] = k['cid']
                data_detail['courseName'] = k['courseName']
                if not k['cover'].startswith('http'):
                    data_detail['cover'] = upload_files.baseUrl + k['cover']
                else:
                    data_detail['cover'] = k['cover']
                data_detail['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data_detail['info'] = k['info']
                data_detail['index'] = index
                res.append(data_detail)
        if count:
            count = count['count(*)']
    except Exception as e:
        print e
        res = []
        code = util.CODE_ERROR
        count = 0
        title = ""
        sid = ""
    data = {
        'code': code,
        'res': res,
        'count': count,
        'title': title,
        'sid': sid
    }
    return util.to_json(data)
